import { BattleArea, BattleAreaActionType, BattleAreaActionTypeMap, BattleAreaType, BattleAreaTypeMap, BattleAreaTypeOptions, BattleAreaTypeSwitchOptions, UaCard } from "../../../models/ua-card.model";
import { UaUserDeckDto } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";

// pages/user/deck-test/deck-test.page.ts
Page({

    /**
     * 页面的初始数据
     */
    data: {
        FILE_HOST: GlobalService.FILE_HOST,
        areas: {} as BattleArea,
        BattleAreaType: BattleAreaType,
        BattleAreaTypeMap: BattleAreaTypeMap,
        changeHandOnce: false,
        FL: [BattleAreaType.F1, BattleAreaType.F2, BattleAreaType.F3, BattleAreaType.F4],
        EL: [BattleAreaType.E1, BattleAreaType.E2, BattleAreaType.E3, BattleAreaType.E4],
        CR: [BattleAreaType.LIFE, BattleAreaType.REMOVE, BattleAreaType.DISPLAY, BattleAreaType.OUTSIDE, BattleAreaType.DECK],
        CR2: [BattleAreaType.HAND, BattleAreaType.OP],
        activeStatus: {} as { [key: string]: boolean },
        selectedType: '' as BattleAreaType,
        actionType: '',
        selectedIndex: -1,
        detailVisible: false,
        detailCard: {} as UaCard,
        BattleAreaTypeOptions: BattleAreaTypeOptions,
        BattleAreaTypeSwitchOptions: BattleAreaTypeSwitchOptions,
        BattleAreaActionType: BattleAreaActionType,
        BattleAreaActionTypeMap: BattleAreaActionTypeMap,
        BACK_IMG: GlobalService.FILE_HOST + '/jp/images/cardlist/card/img_card_jp.png'
    },

    customData: {
        deckCardList: [] as number[],
        ipId: undefined as number | undefined,
        deckId: undefined as number | undefined,
        cardMap: {} as { [key: number]: UaCard },
        shuffled: [] as number[],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options: any) {
        wx.setNavigationBarTitle({
            title: '卡组测试'
        });
        UserDeckService.findById(options.deckId!).then((response: UaUserDeckDto) => {
            if (response) {
                const cardMap: { [key: number]: UaCard } = {}
                const cardList = response.cardDtoList ?? [];
                cardList.map((card: UaCard) => {
                    card.cardImgSm = card.cardImg?.replace('.png', '.jpg');
                    cardMap[card.id!] = card;
                });
                this.customData.cardMap = cardMap;
                const deckCardList = [];
                for (const item of response.cardList ?? []) {
                    for (let i = 0; i < item.count; i++) {
                        deckCardList.push(item.id);
                    }
                }
                this.customData.deckCardList = deckCardList;
                this.shuffle();
            }
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    shuffle() {
        const shuffled = JSON.parse(JSON.stringify(this.customData.deckCardList));
        let n = shuffled.length;
        let r = 0;
        while (n > 0) {
            r = Math.floor(Math.random() * n);
            n--;
            let temp = shuffled[n];
            shuffled[n] = shuffled[r];
            shuffled[r] = temp;
        }
        this.customData.shuffled = shuffled;
        this.preparePlayground();
    },

    changeHand() {
        const rest = [...JSON.parse(JSON.stringify(this.data.areas[BattleAreaType.DECK])), ...JSON.parse(JSON.stringify(this.data.areas[BattleAreaType.HAND]))] as UaCard[];
        const hand = JSON.parse(JSON.stringify(this.data.areas[BattleAreaType.LIFE])) as UaCard[];
        for (const item of rest) {
            item.asFold = true;
        }
        for (const item of hand) {
            item.asFold = false;
        }
        let n = rest.length;
        let r = 0;
        while (n > 0) {
            r = Math.floor(Math.random() * n);
            n--;
            let temp = rest[n];
            rest[n] = rest[r];
            rest[r] = temp;
        }
        const life = rest.splice(0, 7);
        const areas = new BattleArea();
        areas[BattleAreaType.LIFE] = life;
        areas[BattleAreaType.HAND] = hand;
        areas[BattleAreaType.DECK] = rest;
        this.setData({
            changeHandOnce: true,
            areas
        })

    },

    preparePlayground() {
        const hand: UaCard[] = [];
        const life: UaCard[] = [];
        const deck: UaCard[] = [];
        for (let i = 0; i < 7; i++) {
            const cid = this.customData.shuffled.shift();
            hand.push(JSON.parse(JSON.stringify(this.customData.cardMap[cid!])));
        }
        for (let i = 0; i < 7; i++) {
            const cid = this.customData.shuffled.shift();
            const card = JSON.parse(JSON.stringify(this.customData.cardMap[cid!])) as UaCard;
            card.asFold = true;
            life.push(card);
        }
        while (this.customData.shuffled.length > 0) {
            const cid = this.customData.shuffled.shift();
            const card = JSON.parse(JSON.stringify(this.customData.cardMap[cid!])) as UaCard;
            card.asFold = true;
            deck.push(card);
        }

        const areas = new BattleArea();
        areas[BattleAreaType.DECK] = deck;
        areas[BattleAreaType.HAND] = hand;
        areas[BattleAreaType.LIFE] = life;

        this.setData({
            areas,
            changeHandOnce: false
        });
    },

    // 从某区域移动第n张卡片到某区域的上或下，可能可以以盖牌形式显示
    move(fromType: BattleAreaType, fromIdx: number, toType: BattleAreaType, toBottom: boolean, asFold: boolean) {
        let moved = false;
        if (this.data.areas[fromType][fromIdx]) {
            const card = this.data.areas[fromType].splice(fromIdx, 1)[0];
            card.asFold = asFold;
            if (toBottom) {
                this.data.areas[toType].push(card);
            } else {
                this.data.areas[toType].unshift(card);
            }
            moved = true;
        }
        if (moved) {
            this.setData({
                changeHandOnce: true,
                areas: this.data.areas
            });
        }
    },

    switchAreaCards(toType: BattleAreaType) {
        const cardsFrom = JSON.parse(JSON.stringify(this.data.areas[this.data.selectedType]));
        const cardsTo = JSON.parse(JSON.stringify(this.data.areas[toType]));
        this.data.areas[this.data.selectedType] = cardsTo;
        this.data.areas[toType] = cardsFrom;
        this.setData({
            changeHandOnce: true,
            areas: this.data.areas
        });
    },

    changeFoldState() {
        this.data.areas[this.data.selectedType][this.data.selectedIndex].asFold = !this.data.areas[this.data.selectedType][this.data.selectedIndex].asFold;
        this.setData({
            changeHandOnce: true,
            areas: this.data.areas
        })
    },

    onDetailVisibleChange(e: any) {
        this.setData({
            detailVisible: e.detail.visible,
        });
    },

    showType(e: any) {
        const type = e.currentTarget.dataset['type'];
        console.log(type)
        if (this.data.actionType) {
            if (this.data.actionType === BattleAreaActionType.SWITCH) {
                if (type !== BattleAreaType.F1 &&
                    type !== BattleAreaType.F2 &&
                    type !== BattleAreaType.F3 &&
                    type !== BattleAreaType.F4 &&
                    type !== BattleAreaType.E1 &&
                    type !== BattleAreaType.E2 &&
                    type !== BattleAreaType.E3 &&
                    type !== BattleAreaType.E4) {
                    return;
                }
                this.switchAreaCards(type);
            } else {
                let bottom = false;
                let fold = false;
                switch (this.data.actionType) {
                    case BattleAreaActionType.MOVE_BOTTOM:
                        bottom = true;
                        break;
                    case BattleAreaActionType.FOLD_TOP:
                        fold = true;
                        break;
                    case BattleAreaActionType.FOLD_BOTTOM:
                        fold = true;
                        bottom = true;
                        break;
                }
                this.move(this.data.selectedType, this.data.selectedType === BattleAreaType.DECK ? 0 : this.data.selectedIndex, type, bottom, fold);
            }
        }
        this.setData({
            selectedType: this.data.selectedType === type ? !!this.data.actionType ? this.data.selectedType : '' : type,
            actionType: '',
            selectedIndex: -1
        })
    },

    displayDetailCard() {
        this.setData({
            detailVisible: true,
            detailCard: this.data.areas[this.data.selectedType][this.data.selectedIndex]
        })
    },

    select(e: any) {
        const index = e.currentTarget.dataset['index'];
        if (this.data.selectedIndex !== index) {
            this.setData({
                selectedIndex: index
            })
        } else {
            if (!this.data.areas[this.data.selectedType][this.data.selectedIndex].asFold) {
                this.displayDetailCard()
            }
        }
    },

    onPrev() {
        const cardList = this.data.areas[this.data.selectedType];
        let p = this.data.selectedIndex;
        if (p === 0) {
            p = cardList.length - 1;
        } else {
            p--;
        }
        this.setData({
            detailCard: cardList[p],
            selectedIndex: p
        })
    },

    onNext() {
        const cardList = this.data.areas[this.data.selectedType];
        let p = this.data.selectedIndex;
        if (p === cardList.length - 1) {
            p = 0;
        } else {
            p++;
        }
        this.setData({
            detailCard: cardList[p],
            selectedIndex: p
        })
    },

    // 特殊事件: 从卡组顶抽牌
    draw() {
        this.move(BattleAreaType.DECK, 0, BattleAreaType.HAND, false, false);
    },

    // 特殊事件: 从卡组顶看1张牌
    takeLook() {
        this.move(BattleAreaType.DECK, 0, BattleAreaType.OP, false, false);
    },

    // 特殊事件: 从生命区揭示一张，查看触发
    trigger() {
        this.move(BattleAreaType.LIFE, this.data.selectedIndex, BattleAreaType.OP, false, false);
    },

    cardMoveToTop() {
        const type = BattleAreaActionType.MOVE_TOP;
        this.setData({
            actionType: this.data.actionType === type ? '' : type
        })
    },

    cardMoveToBottom() {
        const type = BattleAreaActionType.MOVE_BOTTOM;
        this.setData({
            actionType: this.data.actionType === type ? '' : type
        })
    },

    cardSwitch() {
        const type = BattleAreaActionType.SWITCH;
        this.setData({
            actionType: this.data.actionType === type ? '' : type
        })
    },

    statusSwitch() {
        const statusMap = this.data.activeStatus;
        statusMap[this.data.selectedType] = !statusMap[this.data.selectedType];
        this.setData({
            activeStatus: statusMap
        })
    },

    cardFoldToTop() {
        const type = BattleAreaActionType.FOLD_TOP;
        this.setData({
            actionType: this.data.actionType === type ? '' : type
        })
    },

    cardFoldToBottom() {
        const type = BattleAreaActionType.FOLD_BOTTOM;
        this.setData({
            actionType: this.data.actionType === type ? '' : type
        })
    },

})